#include "resetdialog.h"
#include "ui_resetdialog.h"
#include "singleton.h"
#include "httpmgr.h"
#include "global.h"

#include <QRegularExpression>
#include <QJsonDocument>

ResetDialog::ResetDialog(QWidget *parent)
    : QDialog(parent)
    , ui(new Ui::ResetDialog)
{
    ui->setupUi(this);


    //设置标签的状态类型
    ui->new_pwd_label->SetState("unvisible","unvisible_hover","","visible",
                               "visible_hover","");
    ui->new_pwd_label_2->SetState("unvisible","unvisible_hover","","visible",
                                  "visible_hover","");

    _SetConnect();
    _InitHandlers();
}

ResetDialog::~ResetDialog()
{
    delete ui;
}

void ResetDialog::_SetConnect()
{
    // 检查用户输入
    connect(ui->user_edit, &QLineEdit::editingFinished, this, &ResetDialog::_CheckInput);
    connect(ui->email_edit, &QLineEdit::editingFinished, this, &ResetDialog::_CheckInput);
    connect(ui->code_edit, &QLineEdit::editingFinished, this, &ResetDialog::_CheckInput);
    connect(ui->pwd_edit, &QLineEdit::editingFinished, this, &ResetDialog::_CheckInput);
    connect(ui->pwd_edit_2, &QLineEdit::editingFinished, this, &ResetDialog::_CheckInput);

    //切换密码显示状态
    connect(ui->new_pwd_label, &ClickedLabel::clicked, this, [this]() {
        auto state = ui->new_pwd_label->GetCurState();
        if(state == ClickLbState::Normal){
            ui->pwd_edit->setEchoMode(QLineEdit::Password);
        }else{
            ui->pwd_edit->setEchoMode(QLineEdit::Normal);
        }
        qDebug() << "Label was clicked!";
    });
    connect(ui->new_pwd_label_2, &ClickedLabel::clicked, this, [this]() {
        auto state = ui->new_pwd_label_2->GetCurState();
        if(state == ClickLbState::Normal){
            ui->pwd_edit_2->setEchoMode(QLineEdit::Password);
        }else{
            ui->pwd_edit_2->setEchoMode(QLineEdit::Normal);
        }
        qDebug() << "Label was clicked!";
    });


    connect(MagicSingleton<HttpMgr>::GetInstance().get(),&HttpMgr::sig_reset_mod_finish,
        this, &ResetDialog::_SlotResetModFinish);
}



void ResetDialog::_InitHandlers()
{
    //获取验证码回调处理
    this->_handlers.insert(ReqId::ID_GET_VARIFY_CODE, [this](const QJsonObject& json){
        ui->err_label->clear();
        int error = json["code"].toInt();
        if(error != ErrorCode::SUCCESS)
        {
            ui->err_label->setStyleSheet("color: red;");
            ui->err_label->setText("json 参数错误");
            qDebug() << "error message: " << json["msg"].toString();
            return;
        }

        auto email = json["email"].toString();
        ui->err_label->setStyleSheet("color: green;");
        ui->err_label->setText("验证码已发送到邮箱，注意查收");
    });

    //修改密码回调处理
    this->_handlers.insert(ReqId::ID_RESET_PWD, [this](const QJsonObject& json){
        ui->err_label->clear();
        int error = json["code"].toInt();
        if(error != ErrorCode::SUCCESS)
        {
            ui->err_label->setStyleSheet("color: red;");
            ui->err_label->setText("json 参数错误");
            qDebug() << "error message: " << json["msg"].toString();
            return;
        }

        auto email = json["email"].toString();
        ui->err_label->setStyleSheet("color: green;");
        ui->err_label->setText("密码重置成功");
    });
}

void ResetDialog::_SlotResetModFinish(ReqId id, ErrorCode err, QString res)
{
    ui->err_label->clear();
    ui->err_label->setStyleSheet("color: red;");
    if(err != ErrorCode::SUCCESS)
    {
        qDebug() << "slot_reg_mod_finish errorCode: " << err;
        ui->err_label->setText("网络请求错误");
        return;
    }

    //解析 json
    QJsonDocument jsonDoc = QJsonDocument::fromJson(res.toUtf8());
    if(jsonDoc.isNull())
    {
        ui->err_label->setText("json 解析失败");
        qDebug() << __FILE__ << ":" << __LINE__ << "  json 解析失败";
        return;
    }
    if(!jsonDoc.isObject())
    {
        ui->err_label->setText("json 解析错误");
        qDebug() << __FILE__ << ":" << __LINE__ << "  json 解析错误";
        return;
    }

    //根据id回调指定的函数
    _handlers[id](jsonDoc.object());

    return;
}

bool ResetDialog::_CheckUserInput()
{
    // 清空错误提示
    ui->err_label->clear();
    // 设置错误标签文字颜色为红色
    ui->err_label->setStyleSheet("color: red;");

    // 检查用户名
    if (ui->user_edit->text().isEmpty()) {
        ui->err_label->setText("用户名不能为空");
        return false;
    }

    if(ui->email_edit->text().isEmpty())
    {
        ui->err_label->setText("邮箱不能为空");
        return false;
    }

    auto email = ui->email_edit->text();
    QRegularExpression regex(R"((\w+)(\.|_)?(\w*)(\.(\w+))+)");
    if(!regex.match(email).hasMatch())
    {
        ui->err_label->setText("邮箱格式不正确");
        return false;
    }

    if(ui->code_edit->text().isEmpty())
    {
        ui->err_label->setText("验证码不能为空");
        return false;
    }

    // 检查新密码
    if (ui->pwd_edit->text().isEmpty()) {
        ui->err_label->setText("新密码不能为空");
        return false;
    }
    if(ui->pwd_edit->text().length() < 6)
    {
        ui->err_label->setText("密码长度不能小于6位");
        return false;
    }

    // 检查确认密码
    if (ui->pwd_edit_2->text().isEmpty()) {
        ui->err_label->setText("确认密码不能为空");
        return false;
    }

    // 检查新密码和确认密码是否一致
    if (ui->pwd_edit->text() != ui->pwd_edit_2->text()) {
        ui->err_label->setText("新密码和确认密码不一致");
        return false;
    }

    // 如果所有输入都正确，清除错误提示
    ui->err_label->clear();
    // 设置错误标签文字颜色为绿色
    ui->err_label->setStyleSheet("color: green;");
    return true;
}

void ResetDialog::_CheckInput()
{
    _CheckUserInput();
}

void ResetDialog::on_cancel_btn_clicked()
{
    emit sigSwitchLogin();
}


void ResetDialog::on_confirm_btn_clicked()
{
    if(!_CheckUserInput())
    {
        return;
    }

    QJsonObject json_obj;
    json_obj["username"] = ui->user_edit->text();
    json_obj["email"] = ui->email_edit->text();
    json_obj["password"] = ui->pwd_edit->text();
    json_obj["verificationCode"] = ui->code_edit->text();
    MagicSingleton<HttpMgr>::GetInstance()->PostHttpReq(QUrl(gate_url_prefix+"/modify_password"),
                                                        json_obj, ReqId::ID_RESET_PWD,Modules::RESET_MOD);
}


void ResetDialog::on_get_code_btn_clicked()
{
    auto email = ui->email_edit->text();
    QRegularExpression regex(R"((\w+)(\.|_)?(\w*)(\.(\w+))+)");
    if(!regex.match(email).hasMatch())
    {
        ui->err_label->clear();
        ui->err_label->setStyleSheet("color: red;");
        ui->err_label->setText("邮箱格式不正确");
        return;
    }

    //请求验证码
    QJsonObject send_json;
    send_json["email"] = email;
    auto url = QUrl(gate_url_prefix + "/get_verification_code");
    MagicSingleton<HttpMgr>::GetInstance()->PostHttpReq(url, send_json,ReqId::ID_GET_VARIFY_CODE, Modules::RESET_MOD);
}

